<?php
namespace app\classes\model;


use app\course\model\CourseModel;
use think\Db;
use think\Log;
use think\Model;
use tree\Tree;


class ClassModel extends Model
{
    public function addClasses($data)
    {
        $result = self::insert($data);
        return $result;
    }

    /**
     * 用户角色
     * @param $uid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function roleAuth($uid, $shop_id=1)
    {
        if(empty($uid)){
            $uid = cmf_get_current_admin_id();
        }

        $roles = Db::name('role')->alias('ro')
            ->field('ro.id,ro.name')
            ->join('role_user ru','ru.role_id=ro.id')
            ->where('ro.status','=',1)//正常启用
            ->where('ro.shop_id','=',$shop_id)
            ->where('ru.user_id','=',$uid)
            ->select();

        return $roles;
    }

    /**
     * 通过字段获取班级
     * @param array $filter
     * @return array|false|\PDOStatement|string|Model
     */
    public function getClassByField($filter=[])
    {
        //默认条件
        $where = [
            'delete_time' => ['eq', 0] //未删除
        ];
        if(!empty($filter) && is_array($filter)){
            $where = array_merge($where,$filter);
        }

        $obj = $this->where($where)->select();

        return $obj;
    }
    /**
     * 通过字段获取班级
     * @param array $filter
     * @return array|false|\PDOStatement|string|Model
     */
    public function getIsClassByField($filter=[])
    {
        //默认条件
        $where = [
            'delete_time' => 0,//未删除
            'is_and_class' => 0, //未并班

        ];
        if(!empty($filter) && is_array($filter)){
            $where = array_merge($where,$filter);
        }

        $obj = $this->where($where)->select();

        return $obj;
    }
    /**
     * 排课课时
     * @param int $class_id  班级
     * @param int $course_start 课程开始时间戳
     * @param int $course_hour  课时总数
     * @param int $shop_id  店铺ID
     * @param array $adjust_date 调课开始和结束时间戳
     * @param int $schedule_num  进度
     * @param string $msg 提示消息
     * @return array|bool
     */
    public function getCourseTime($class_id=0, $course_start=0, $course_hour=0, $shop_id=1, $adjust_date=[], $schedule_num=0, &$msg='')
    {
        $data = [];
        //中文星期
        $gb_week = [
            '1' => '周一','2' => '周二','3' => '周三','4' => '周四',
            '5' => '周五','6' => '周六','7' => '周日',
        ];
        if(empty($class_id) || !is_numeric($class_id)){
            $msg = '班级('.$class_id.')不能为空，排课失败';
            return false;
        }else {
            $class = $this->alias('cl')
                ->field('cl.*,c.course_name,c.course_hour')
                ->join('course c', 'cl.course_id=c.id')
                ->where('cl.shop_id', '=', $shop_id)
                ->where('cl.delete_time', '=', 0)
                ->where('cl.id', '=', $class_id)
                ->find();

            if (count($class) < 1) {
                $msg = '班级('.$class_id.')或课程不存在，排课失败';
                return false;
            }
            //开课时间
            if(empty($course_start)){
                $course_start = $class['start_lesson_time'];
            }

            //课时数
            if(empty($course_hour)){
                $course_hour = $class['course_hour'];
            }

            if(empty($schedule_num) || !is_numeric($schedule_num)){
                //进度
                $schedule_num = 1;
            }else{
                //新的课时数
                $course_hour = $course_hour - $schedule_num + 1;
                if($course_hour <= 0){
                    $course_hour = 1;
                }
            }

            //开始上课时间是周几
            $start_week = date('N', $course_start);

            //假期
            $holidays = Db::name('holiday')
                ->field('id,date')
                ->where('shop_id', '=', $shop_id)
                ->where('date', '>= time', $course_start)
                ->order('date', 'asc')
                ->select();
            if(count($holidays) > 0){
                $holidays = $holidays->toArray();
                $holiday_date = array_column($holidays,'date');
            }else{
                $holiday_date = [];
            }

            //多个开课时段
            $week = explode(',', $class['class_start_week']);
            $start_time = explode(',', $class['class_time_start']);
            $end_time = explode(',', $class['class_time_end']);
            //每周课时数
            $per_week_total = count($week);

            for ($i = 0; $i < $per_week_total; $i++) {
                $data[$i]['week'] = intval($week[$i]);
                $data[$i]['start_time'] = $start_time[$i];
                $data[$i]['end_time'] = $end_time[$i];
                $data[$i]['cur_week'] = $gb_week[$week[$i]];
                $data[$i]['class_id'] = $class['id'];
                $data[$i]['classroom_id'] = $class['classroom_id'];
                $data[$i]['teacher_id'] = $class['teacher_id'];
            }
            //原始数据
            $initial_data = $data;
            //对数组进行升序并保持索引关系(数字索引不保持)
            sort($data);
            //相邻周几之间的天数差值
            for($i=0; $i<$per_week_total; $i++){
                if($i == 0){
                    $data[$i]['add'] = ($data[$i]['week'] + 7) - $data[$per_week_total-1]['week'];
                }elseif($i < $per_week_total){
                    $data[$i]['add'] = $data[$i]['week'] - $data[$i-1]['week'];
                }else{
                    $data[$i]['add'] = $data[$i]['week'] - $data[$i-1]['week'];
                }
            }

            //排序后原始数据
            $new_data = $data;
            //第一周上课课时
            foreach ($data as $key => $val) {
                if ($val['week'] < $start_week) {
                    //开课时间小于所设置的周几开课
                    unset($data[$key]);
                    continue;
                }
                $day = $val['week'] - $start_week;
                $start_timestamp = strtotime("+$day days", $course_start);
                if(array_search($start_timestamp, $holiday_date) !== false){
                    //是假期
                    unset($data[$key]);
                    continue;
                }
                if(!empty($adjust_date) && count($adjust_date) == 2){
                    if( ($start_timestamp >= $adjust_date[0]) && ($start_timestamp <= $adjust_date[1]) ){
                        //是调课时间
                        unset($data[$key]);
                        continue;
                    }
                }

                $course_start_date = date('Y-m-d', $start_timestamp);
                $data[$key]['date'] = $course_start_date;
            }

            //总课时不足上一周
            if ($course_hour <= $per_week_total) {
                $data = array_slice($data, 0, $course_hour);
            }else{
                //第一周上课课时数
                $first_week_total = count($data);
                //从第二周开始剩余课时数
                $hours_left = $course_hour - $first_week_total;
                $new_left_hours = $hours_left;

                $item = 0;//标记成功记录了几个课时
                $day_week = 0;//标记星期天数
                $start_timestamp = 0;//日期时间戳
                for ($j = 0; $j <= $hours_left; $j++) {
                    for ($i = 0; $i < $per_week_total; $i++) {
                        if($item == $new_left_hours){
                            //已到达课时总数
                            break;
                        }
                        if(empty($day_week)){
                            $day_week = $new_data[$i]['week'] + 7;
                            $day = $day_week - $start_week;
                            $start_timestamp = strtotime("+$day days", $course_start);
                        }else{
                            $day_week += $new_data[$i]['add'];
                            $day = $new_data[$i]['add'];
                            $start_timestamp = strtotime("+$day days", $start_timestamp);
                        }

                        if(array_search($start_timestamp, $holiday_date) !== false){
                            //是假期
                            $hours_left += 1;
                            continue;
                        }
                        if(!empty($adjust_date) && count($adjust_date) == 2){
                            if( ($start_timestamp >= $adjust_date[0]) && ($start_timestamp <= $adjust_date[1]) ){
                                //是调课时间
                                $hours_left += 1;
                                continue;
                            }
                        }
                        $course_start_date = date('Y-m-d', $start_timestamp);

                        $res['week'] = $day_week;
                        $res['cur_week'] = $new_data[$i]['cur_week'];
                        $res['start_time'] = $new_data[$i]['start_time'];
                        $res['end_time'] = $new_data[$i]['end_time'];
                        $res['class_id'] = $class['id'];
                        $res['classroom_id'] = $class['classroom_id'];
                        $res['teacher_id'] = $class['teacher_id'];
                        $res['date'] = $course_start_date;
                        array_push($data, $res);
                        $item += 1;
                    }
                }
            }

            //按日期排序
            sortArrByField($data,'date');
            $last_total = count($data);
            if($last_total > 0){
                foreach ($data as $k=>$v){
                    $data[$k]['schedule'] = ($k + $schedule_num);
                }
            }
            return $data;
        }
    }

         /*
        * 课程进度
        * @param class_id  排序数组
        * @return array
        */
    public function progress($class_id)
    {
        //课程的model
        $course_model=new CourseModel();
        $course_id=$this->where(['id'=>$class_id])->value('course_id');
        $start_lesson=$this->where(['id'=>$class_id])->value('start_lesson_time');
        $length=$course_model->where(['id'=>$course_id])->value('course_hour');
        $sort_date=Db::name('course_schedule')->where(['class_id'=>$class_id])->order('id asc')->select();


        if(!$sort_date)
        {
            return  $data=[
                'status'=>0,
                'progress'=>0,
            ];
        }
        if ($sort_date->isEmpty()) {
            $data=[
                'status'=>2,
                'progress'=>'0',
            ];
            return json_encode($data);
        }
        if($sort_date->isEmpty())
        {
            $data=[
                'status'=>2,
                'progress'=>'0',
            ];
            return json_encode($data);
        }
        $sort_date=$sort_date->toArray();
        $date_length=count($sort_date);
        $first_lesson_day=$sort_date[0]['date'];
        $end_lesson_day=$sort_date[$date_length-1]['date'];

         $now=time();
        if($first_lesson_day>$now)
        {
            $data=[
                'status'=>0,
                'progress'=>0,
               ];
            $this->where(['id'=>$class_id])->update(['class_status'=>0]);
        }
        if($now>$first_lesson_day && $now<=$end_lesson_day)
        {
            $progress=0;
            $j=1;
           foreach($sort_date as $k=>$v)
           {
               if(!empty($sort_date[$k-1]))
               {
                   if(($now<$v['date']) && ($now>$sort_date[$k-1]['date']))
                   {
                       $j=$k;
                   }
               }else{
                   $j=$k;
               }

           }
            $this->where(['id'=>$class_id])->update(['class_status'=>1]);

            $data=[
                'status'=>1,
                'progress'=>$j,
            ];
        }
        if($now>$end_lesson_day)
        {
            $this->where(['id'=>$class_id])->update(['class_status'=>2]);
            Db::name('order')->where(['id'=>$class_id])->update(['order_status'=>2]);
            $data=[
                'status'=>2,
                'progress'=>$date_length,
            ];
        }
        return  json_encode($data);
    }
    /*
     * 老师汇按着今天的往后排序
     */
    public function teacher_lesson($class_id)
    {
        $start_lesson=$this->where(['id'=>$class_id])->value('start_lesson_time');
        $sort_date=$this->getCourseTime($class_id);
        $date_length=count($sort_date);
        $first_lesson_day=strtotime($sort_date[0]['date']);
        $end_lesson_day=strtotime($sort_date[$date_length-1]['date']);
        $now=time();
        $data=[];
        foreach($sort_date as $k=>$v)
        {
            //结课
            if ($now > $end_lesson_day)
                {
                    $data = [$end_lesson_day.'结课了'];
                }
            //未开课
            if($now<$first_lesson_day)
              {
                  $data[]=$v['date'];
              }
            //进行中
            if (!empty($sort_date[$k-1]) && $now>$first_lesson_day && $now<$end_lesson_day )
                {
                    if (($now < strtotime($v['date'])))
                        {
                            $data[]=$sort_date[$k]['date'];
                        }
                 }
        }
        $data['class_id']=$class_id;
        return $data;
    }

    /**
     * 释放座位
     * @param $class_id
     * @param $student_id
     * @param int $shop_id
     * @return bool
     */
    public function releaseSeat($class_id, $student_id, $shop_id=1)
    {
        $result = true;
        if(empty($class_id) || empty($student_id) || !is_numeric($class_id) || !is_numeric($student_id)){
            return false;
        }

        $seat_where = [
            'student_id' => $student_id,
            'classes_id' => $class_id,
            'shop_id' => $shop_id,
        ];
        $class_student_where = [
            'student_id' => $student_id,
            'class_id' => $class_id,
        ];

        self::startTrans();
        try {
            $seat = Db::name('class_seat')->where($seat_where)->find();
            if(count($seat) > 0) {
                //删除座位
                Db::name('class_seat')->where(['id' => $seat['id']])->delete();
                //班级报名人数减一
                $this->where(['id' => $class_id])->setDec('current_num');
            }

            $class_student = Db::name('class_student')->where($class_student_where)->find();
            if(count($class_student) > 0) {
                //从班级中删除学生
                Db::name('class_student')->where(['id' => $class_student['id']])->delete();
            }

            self::commit();
        } catch (\Exception $e) {
            self::rollback();
            $result = false;
        }

        return $result;
    }
    /*
     *
     */
    public function addPost($post)
    {

    }
}

